package com.ux.iot.jetlinks.service.websocket;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.ux.iot.core.constant.ErrorCode;
import com.ux.iot.core.exception.IotClientConnectException;
import com.ux.iot.core.service.AbstractServiceClient;
import com.ux.iot.jetlinks.bo.LoginInfo;
import com.ux.iot.jetlinks.pro.WebsocketProperties;
import com.ux.iot.jetlinks.service.auth.JetlinkTokenManager;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;

import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author caixiaodao
 * @version 1.0
 * 功能描述
 * jetlink websocket 客户端
 * @date 2021/11/15 10:32
 */
@Slf4j
@AllArgsConstructor
@Getter
public class SampleJetlinksWebosocketClient extends AbstractServiceClient {
    WebsocketProperties websocketProperties;
    JetlinkTokenManager jetlinkTokenManager ;
    SingleWebsocketClientEndpoint endpoint;
    static String token;

    @Override
    public void init() {
        LoginInfo loginInfo= null;
        try {
            loginInfo = jetlinkTokenManager.getToken();
            log.info("获取jetlinks 系统授权信息{}", JSON.toJSONString(loginInfo));
            if(ObjectUtil.isNull(loginInfo)){
                throw new IotClientConnectException(ErrorCode.AUTH_EXCEPTION,"登陆jetlinks 失败 返回参数为空");
            }else{
                token=loginInfo.getToken();
            }
        } catch (Exception e) {
            throw new IotClientConnectException(ErrorCode.AUTH_EXCEPTION,e.getMessage());
        }


    }
    @Async
    @Retryable(maxAttempts =100,backoff = @Backoff(delay = 5000l,multiplier = 1))
    public void start()  {
        init();// 初始化参
        WebSocketContainer socketContainer=ContainerProvider.getWebSocketContainer();
        socketContainer.setAsyncSendTimeout(3000);
        try {
            String uri=websocketProperties.getJetlinkWebsocketUrl().concat("/").concat(token);
            log.info("连接websocket服务器 {}",uri);
            socketContainer.connectToServer(endpoint,new URI(uri));
        } catch (DeploymentException e) {
            throw new IotClientConnectException(ErrorCode.CONNECT_EXCEPTION,e.getMessage());
        } catch (IOException e) {
            throw new IotClientConnectException(ErrorCode.CONNECT_EXCEPTION,e.getMessage());
        } catch (URISyntaxException e) {
            throw new IotClientConnectException(ErrorCode.CONNECT_EXCEPTION,e.getMessage());
        }
    }
    @Recover
    public void stop() {

        log.error("连接不上jetlinks 服务器,停止连接");
    }
}
